package com.xaicode.auth.security.satoken;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.xaicode.auth.security.AuthConst;
import com.xaicode.auth.security.LoginUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 自定义 Sa-Token 注解判定数据处理
 * <p>
 * 支持{@link SaCheckRole}和{@link SaCheckPermission}
 * <p>
 * 本类中的<code>StpUtil.getSession().getDataMap()</code>数据来自 asl-auth 模块的认证处理
 * 
 * @date 2025/1/7
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "sa-token-enabled", havingValue = "true")
@ConditionalOnMissingClass("cn.dev33.satoken.stp.StpInterface")
public class StpInterfaceImpl implements StpInterface {

    static {
        log.info("[Self-Common-Auth][Sa-Token] 加载自定义 StpInterface 处理");
    }

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        log.debug("getPermissionList {} {}", loginId, loginType);
        List<String> l = Lists.newArrayList();

        // 超级管理员跳过一切检查
        if (LoginUtil.isAdminLogin()) {
            l.add(AuthConst.ADMIN_PERMISSION);
            return l;
        }

        /*
        "dataMap":{
            "role":[..],
            "user":{"deptId": xx},
            "permission": ["p1", "p2"]
        }
         */
        Map<String, Object> dataMap = StpUtil.getSession().getDataMap();
        JSONArray permissionJsonArray = (JSONArray) dataMap.get("permission");
        for (Object permissionJson : permissionJsonArray) {
            String permission = (String) permissionJson;
            l.add(permission);
        }

        return l;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.debug("getRoleList {} {}", loginId, loginType);
        List<String> l = Lists.newArrayList();

        // 超级管理员跳过一切检查
        if (LoginUtil.isAdminLogin()) {
            l.add(AuthConst.ADMIN_ROLE);
            return l;
        }

        /*
        "dataMap":{
            "role":[{"dataScope":1,"roleId":11,"roleKey":"test1","roleName":"test1"}],
            "user":{..},
            "permission": [..]
        }
         */
        Map<String, Object> dataMap = StpUtil.getSession().getDataMap();
        JSONArray roleJsonArray = (JSONArray) dataMap.get("role");
        for (Object roleJson : roleJsonArray) {
            JSONObject roleJsonObj = (JSONObject) roleJson;
            String roleKey = roleJsonObj.getString("roleKey");
            l.add(roleKey);
        }

        return l;
    }

}
